﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JEPy;

namespace aliasBuilder
{
    public partial class Form1 : Form
    {
        PVAliases myAlias;
        public Form1()
        {
            InitializeComponent();
        }

        private void TbAdd_Click(object sender, EventArgs e)
        {
            PVAlias tpv = new PVAlias();
            tpv.Alias = TbAlias.Text;
            tpv.PvName = TbPV.Text;
            tpv.isDevice = CbIsDevice.Checked;
            tpv.isOutput = CbIsOutput.Checked;
            tpv.isRmote = CbIsRemot.Checked;
            myAlias.allPvs.Add(tpv);
            LbPv.Items.Add(tpv.PvName);
        }

        private void TbSave_Click(object sender, EventArgs e)
        {
            SaveFD.ShowDialog();
            string path = SaveFD.FileName;
            myAlias.Save(path);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myAlias = new PVAliases();
        }

        private void TbLoad_Click(object sender, EventArgs e)
        {
            openFD.ShowDialog();
            string path = openFD.FileName;
            myAlias = PVAliases.Load(path);
            updateList();
        }

        private void updateList()
        {
            foreach (PVAlias item in myAlias.allPvs)
            {
                LbPv.Items.Add(item.PvName);
            }
        }

        private void updateProp()
        {
            PVAlias tpv;
            tpv = null;
            foreach (PVAlias item in myAlias.allPvs)
            {
                if (item.PvName == LbPv.Text)
                {
                    tpv = item;
                    break;
                }
            }
            if (tpv == null)
                return;

            TbAlias.Text = tpv.Alias;
            TbPV.Text = tpv.PvName;
            CbIsDevice.Checked=tpv.isDevice;
            CbIsOutput.Checked = tpv.isOutput;
            CbIsRemot.Checked = tpv.isRmote;
        }

        private void TbRemove_Click(object sender, EventArgs e)
        {
            foreach (PVAlias item in myAlias.allPvs)
            {
                if (item.PvName == LbPv.Text)
                {
                    myAlias.allPvs.Remove(item);
                    break;
                }
            }
            LbPv.Items.RemoveAt(LbPv.SelectedIndex);
        }

        private void LbPv_SelectedIndexChanged(object sender, EventArgs e)
        {
            updateProp();
        }
    }
}
